package cn.edu.zjusc.Servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;


import cn.edu.zjusc.ExcelGenerator.InterviewGroupExamGenerator;
import cn.edu.zjusc.ExcelModel.InterviewGroupExamInfo;
import cn.edu.zjusc.POJO.ExamInfo;
import cn.edu.zjusc.POJO.StudentDetailInfo;
import cn.edu.zjusc.Rmi.IExamRemote;
import cn.edu.zjusc.Rmi.IStudentRemote;

/**
 * Servlet implementation class InterviewGroupExamServlet
 */
public class InterviewGroupExamServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public InterviewGroupExamServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		System.out.println("-----------post---------");
		response.setHeader("Charset", "UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		//response.setContentType("text/json"); // 解决后台数据中文乱码
		response.setCharacterEncoding("UTF-8");

		// 不要多次取writer对象
		//PrintWriter out = response.getWriter(); // 输出流
		
		int interviewGroupExamId=Integer.parseInt(request.getParameter("interviewGroupExamId"));
		
		System.out.println("--------------interviewGroupExamId-------:"+interviewGroupExamId);
		try {
			InterviewGroupExamServletGenerator(request,response,interviewGroupExamId);
		} catch (InvalidFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void InterviewGroupExamServletGenerator(HttpServletRequest request, HttpServletResponse response,int interviewGroupExamId) throws NamingException, InvalidFormatException, IOException{
		System.out.println("-----------开始生成面试组考表---------");
		// 不要多次取writer对象
		PrintWriter out = response.getWriter(); // 输出流
		
		InitialContext jndiContext=new InitialContext();
		Object ref=jndiContext.lookup("StudentEjbRemote");
		IStudentRemote ss2=(IStudentRemote)PortableRemoteObject.narrow(ref, IStudentRemote.class);
		//根据考场号，获得数据库中学生名单list，数据为全部信息
		List<StudentDetailInfo> roomNumStudentList=ss2.GetAllStudentBaseInfoByAuditionGroup(interviewGroupExamId);
		if(roomNumStudentList.size()==0){
			out.print("<script>alert('对不起，该面试考场人数为0，请为该考场分配考试或更换考场。');</script>");
			return ;
		}
		System.out.println("-----------roomNumStudentList---大小------"+roomNumStudentList.size());
		
		//以下为考试信息
		System.out.println("---------------考试信息-------------");
		InitialContext jndiContext2=new InitialContext();
		Object ref2=jndiContext2.lookup("ExamEjbRemote");
		IExamRemote ss3=(IExamRemote)PortableRemoteObject.narrow(ref2, IExamRemote.class);
		List<ExamInfo> examList=ss3.GetAllExamInfoByRoomNum(interviewGroupExamId);
		if(examList.size()==0){
			out.print("<script>alert('对不起，该面试考场未分配考试，请为该考场分配考试。');</script>");
			return ;
		}
		//设置组考表学生信息list，数据为组考表中需要的信息
		List<InterviewGroupExamInfo> studentList=new ArrayList<InterviewGroupExamInfo>();
		//向studentList中赋值，数值来自于roomNumStudentList
		for(int i=0;i<roomNumStudentList.size();i++){
			InterviewGroupExamInfo studentGroupInfo=new InterviewGroupExamInfo(roomNumStudentList.get(i).getExtendInfoBean().getStuext_examCardID(),roomNumStudentList.get(i).getStubs_name(),roomNumStudentList.get(i).getMajorCode().getMa_majorName(),roomNumStudentList.get(i).getEduBkInfoBean().getStuedu_unGrdtSchoolBean().getUnicd_unysyName(),roomNumStudentList.get(i).getEduBkInfoBean().getStuedu_unGrdtMajor());
			studentList.add(studentGroupInfo);
		}
		
		InterviewGroupExamGenerator interviewGroupExamGenerator=new InterviewGroupExamGenerator();
		//获取系统路径
		String realWebPhysicalPath = getServletContext().getRealPath(
		"/");
		//模板路径
		String input=realWebPhysicalPath+"userfiles/template/interviewgroupexam.xls";
		//文件路径
		String output=realWebPhysicalPath+"userfiles/examcert/InterviewGroupExam"+interviewGroupExamId+".xls";
		//生成面试组考表
		System.out.println("-----------开始生成面试组考表------");
		interviewGroupExamGenerator.modify(input,output, studentList,roomNumStudentList.get(0).getExtendInfoBean().getStuext_theYear(),
				roomNumStudentList.get(0).getExtendInfoBean().getStuext_theSeason(),
				roomNumStudentList.get(0).getExtendInfoBean().getStuext_examPlace(),interviewGroupExamId,examList.get(0).getStartTime());	//,roomNumStudentList.get(0).getExtendInfoBean().getStuext_theYear(),roomNumStudentList.get(0).getExtendInfoBean().getStuext_theSeason(),roomNumStudentList.get(0).getExtendInfoBean().getStuext_examPlace(),interviewGroupExamId
		System.out.println("-----------生成面试组考表完毕------");
		
		//文件传输
		//传输数据流
		ServletOutputStream outer=null;
//		//获取系统路径
//		String realWebPhysicalPath = getServletContext().getRealPath(
//		"/");
		File file = new File(realWebPhysicalPath+"userfiles/examcert/InterviewGroupExam"+interviewGroupExamId+".xls");
		String fileName = file.getName();
		System.out.println("-----------fileName---------");
		System.out.println(fileName);
		if (file.exists() && file.canRead()) {
			response.reset();
			response.setContentType("application/x-msdownload");
			response.setHeader("Content-Disposition",
					"attachment;filename=\""
							+ new String(fileName
									.getBytes("utf-8"),
									"utf-8") + "\"");
			response.setContentLength((int)file.length());
			FileInputStream stream=new FileInputStream(file);	
			try {
				outer=response.getOutputStream();
				byte[] buff = new byte[2048];
				int bytesRead;
				while (-1 != (bytesRead = stream.read(buff))) {
					outer.write(buff, 0, bytesRead);
				}
			} catch (final IOException e) {
				System.out.println("IOException." + e);
			} finally {
				//response.setStatus(response.SC_OK);
				//response.flushBuffer();
				System.out.println("-----------final---------");
				stream.close();
				outer.flush();
				outer.close();
				file.delete();
			}
			//return;
		} else {
			//out.println("File Not Found!!!");
		}
	}
}
